package com.feng.annotation.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.feng.annotation.bean.Car;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.StringValueResolver;

import javax.sql.DataSource;

/**
 * @author Lee
 * @date 2019/3/7
 */
//@Profile("test")
@PropertySource(value = {"classpath:db.properties"})
@Configuration
public class ProfileConfig implements EmbeddedValueResolverAware {

    @Value("${druid.username}")
    private String username;

    private String password;

    @Value("${druid.url}")
    private String url;

    @Profile("default")
    @Bean
    public DataSource dataSource(@Value("${druid.driverClass}") String driverClass){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url + "annotation");
        return dataSource;
    }

    @Profile("test")
    @Bean
    public DataSource testDataSource(@Value("${druid.driverClass}") String driverClass){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url + "zshop");
        return dataSource;
    }

    @Profile("dev")
    @Bean
    public DataSource devDataSource(@Value("${druid.driverClass}") String driverClass){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url + "sys");
        return dataSource;
    }

    @Profile("prod")
    @Bean
    public DataSource prodDataSource(@Value("${druid.driverClass}") String driverClass){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url + "zheng");
        return dataSource;
    }

    @Bean
    public Car car() {
        return new Car();
    }

    @Override
    public void setEmbeddedValueResolver(StringValueResolver resolver) {
        password = resolver.resolveStringValue("${druid.password}");
    }
}
